/**
 * MIT License
 * 
 * Copyright (c) 2017 CaiDongyu
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.tunnel.client.tunnel;

import java.net.InetAddress;

import com.tunnel.client.config.Config;
import com.tunnel.client.task.HttpTaskManager;
import com.tunnel.client.task.TcpTaskManager;
import com.tunnel.common.constant.Constant;
import com.tunnel.common.nio.EventLoopGroupManager;
import com.tunnel.common.tunnel.TunnelBaseHandler;
import com.tunnel.common.tunnel.TunnelDataQueueManager;
import com.tunnel.common.util.LogUtil;
import com.tunnel.common.util.StringUtil;

import io.netty.channel.ChannelHandlerContext;

public class TunnelClientHandler extends TunnelBaseHandler {
	private TunnelClient tunnelClient;
	
	public TunnelClientHandler(TunnelClient tunnelClient) {
		super("Tunnel-Client");
		this.tunnelClient = tunnelClient;
	}
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
		registerToServer(ctx);
	}
	
	protected void registerToServer(ChannelHandlerContext ctx){
		//连接成功，设置全局对象
		TunnelChannelHandlerContextManager.setChannelHandlerContext(ctx);
		//注册
		String localHost = "...";
		try {
			localHost = InetAddress.getLocalHost().getHostAddress();
		} catch (Exception e) {
			LogUtil.error(e);
		}
		String content = Config.NAME + "[" + localHost + "]" + Constant.SPLIT_FLAG + 
						(StringUtil.isEmpty(Config.HOST_ARY)?Constant.NULL:Config.HOST_ARY) + Constant.SPLIT_FLAG +
						(StringUtil.isEmpty(Config.TCP_ARY)?Constant.NULL:Config.TCP_ARY);
		TunnelDataQueueManager.commitData(TunnelDataQueueManager.REGISTER_MSG, ctx, content.getBytes());
	}

	@Override
	protected void handleData(ChannelHandlerContext ctx, byte[] data, byte flag) {
		
		switch (flag) {
			case TunnelDataQueueManager.PING_MSG:
	//			LogUtil.log("Tunnel心跳");
				break;
				
			//注册返回结果
			case TunnelDataQueueManager.REGISTER_MSG:
				doRegisterResult(ctx, data);
				break;
			
			//HTTP
			case TunnelDataQueueManager.HTTP_DATA_MSG:
				httpDataMsg(ctx, data);
				break;
			case TunnelDataQueueManager.STOP_HTTP_TASK_MSG:
				stopHttpTaskMsg(ctx, data);
				break;
				
			//TCP
			case TunnelDataQueueManager.TCP_CONNECT_MSG:
				tcpConnectMsg(ctx, data);
				break;
			case TunnelDataQueueManager.TCP_DATA_MSG:
				tcpDataMsg(ctx,data);
				break;
			case TunnelDataQueueManager.TCP_CLOSE_MSG:
				stopTcpTaskMsg(ctx, data);
				break;
			default:
				break;
		}
	}

	public void doRegisterResult(ChannelHandlerContext ctx, byte[] data){
		String result = new String(data);
		LogUtil.log(result);
		if(result.contains("REGISTER FAILED")){
			LogUtil.log("Tunnel-Client Start Failed!!!");
			
			//关闭netty
			EventLoopGroupManager.shutdown(0);

			System.exit(0);//停止程序
		}
	}
	
	public void httpDataMsg(ChannelHandlerContext ctx, byte[] data){
		//前17个字符是
		//host_index(在Config.HOST_LIST里的下标) 占1位
		//requestId 时间戳+三位随机数，代表http请求的编号 占16位
		if(data.length >= 17){
			byte[] hostIndexBytes = new byte[1];
			System.arraycopy(data, 0, hostIndexBytes, 0, 1);
			
			byte[] requestIdBytes = new byte[16];
			System.arraycopy(data, 1, requestIdBytes, 0, 16);
			
			byte[] dataBytes = new byte[data.length-1-16];
			if(dataBytes.length>0){
				System.arraycopy(data, 17, dataBytes, 0, dataBytes.length);
			}
			
			//交给线程池去处理与应用服务器的通讯
			HttpTaskManager.doTask(hostIndexBytes[0], requestIdBytes, dataBytes);
		}
	}
	
	public void stopHttpTaskMsg(ChannelHandlerContext ctx, byte[] data){
		//前16个字符是
		//requestId 时间戳+三位随机数，代表http请求的编号 占16位
		if(data.length >= 16){
			byte[] requestIdBytes = new byte[16];
			System.arraycopy(data, 0, requestIdBytes, 0, 16);
		}
	}
	
	public void tcpConnectMsg(ChannelHandlerContext ctx, byte[] data){
		//前17个字符是
		//port_index(在Config.TCP_LIST里的下标) 占1位
		//connectionId 时间戳+三位随机数，代表TCP连接的编号 占16位
		if(data.length >= 17){
			byte[] portIndexBytes = new byte[1];
			System.arraycopy(data, 0, portIndexBytes, 0, 1);
			
			byte[] connectionIdBytes = new byte[16];
			System.arraycopy(data, 1, connectionIdBytes, 0, 16);
			
			TcpTaskManager.newTask(portIndexBytes[0], connectionIdBytes, ctx);
		}
	}
	
	public void tcpDataMsg(ChannelHandlerContext ctx, byte[] data){
		//前16个字符是
		//connectionId 时间戳+三位随机数，代表TCP连接的编号 占16位
		if(data.length >= 16){
			byte[] connectionIdBytes = new byte[16];
			System.arraycopy(data, 0, connectionIdBytes, 0, 16);
			
			byte[] dataBytes = new byte[data.length-16];
			if(dataBytes.length > 0){
				System.arraycopy(data, 16, dataBytes, 0, dataBytes.length);
			}
			
			//交给线程池去处理与应用服务器的通讯
//			LogUtil.log("收到："+new String(dataBytes));
			TcpTaskManager.sendData2App(new String(connectionIdBytes), dataBytes);
		}
	}

	public void stopTcpTaskMsg(ChannelHandlerContext ctx, byte[] data){
		//前16个字符是
		//connectionId 时间戳+三位随机数，代表TCP连接的编号 占16位
		if(data.length >= 16){
			byte[] connectionIdBytes = new byte[16];
			System.arraycopy(data, 0, connectionIdBytes, 0, 16);
			TcpTaskManager.stopTask(new String(connectionIdBytes));
		}
	}
	
    @Override  
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LogUtil.log("Tunnel-Client tunnel exception");
        LogUtil.error(cause); 
        ctx.close();
    }
	
	@Override
    protected void handleReaderIdle(ChannelHandlerContext ctx) {
        LogUtil.log("Tunnel-Client tunnel timeout");
        super.handleReaderIdle(ctx);
        ctx.close();
    }
	
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        LogUtil.log("Tunnel-Client tunnel closing");
		super.channelInactive(ctx);
		try {
	        //关闭所有Http任务
	        LogUtil.log("closing http task");
	        HttpTaskManager.stopTask();
		} catch (Exception e) {
			LogUtil.error(e);
		}

		try {
	        //关闭所有Tcp任务
	        LogUtil.log("closing tcp task");
	        TcpTaskManager.stopTask();
		} catch (Exception e) {
			LogUtil.error(e);
		}
        LogUtil.log("Tunnel-Client tunnel close success");

		//断线重连
		tunnelClient.connect();
	}

}